<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { showLoading, hideLoading, showToast, redirectTo, reLaunch } from '@tarojs/taro';
import { QUERY_DICT_BY_PARENT_ID } from '/@/api/modules/base/dict';
import { INSERT_APP_WO_DELIVER } from '/@/api/modules/deliver/app-wo-deliver';
import { formState, formRules, state, DeliverType } from './state';
import dayjs from 'dayjs';
const workOrderFormRef = ref();

/**
 * 选择时间区域
 */
function selectedTimeRange(startTime: string, endTime: string) {
  formState.planTimeStart = dayjs(startTime).valueOf();
  formState.planTimeEnd = dayjs(endTime).valueOf();
  state.taskTimePickerVisible = false;
  state.deliverPlanTime = `${startTime} - ${endTime}`;
}

/**
 * @function 上传文件
 * @param imgList
 */
function uploadImageChange(imgList: { key: string; src: string }[]) {
  (
    imgList.map((i) => {
      return {
        fileType: 1,
        fileUrl: i.src,
        fileName: i.src.split('/').reverse()[0],
      };
    }) as AppWoDeliver.FileDto[]
  ).forEach((item) => {
    formState.woDeliverFileDto?.push(item);
  });
}

/**
 * @function 确认提交
 */
function submit() {
  workOrderFormRef.value.validate().then(({ valid }) => {
    if (!valid) return;
    showLoading({ title: '加载中...' });

    INSERT_APP_WO_DELIVER({ woDeliverDto: formState }).then((res) => {
      hideLoading();
      showToast({
        title: res.comResp?.msg || res.comResp?.tip || '',
        icon: 'success',
      });
      redirectTo({
        url: `/pages/deliver/submit-success/index?id=${res.woDeliverDto?.id}`,
      });
    });
  });
}

onMounted(() => {
  state.deliverTypeList = [];
  // 工单类型
  QUERY_DICT_BY_PARENT_ID({
    parentTag: 'deliver_type',
  }).then((res) => {
    if (!res.content || !res.content.length) return;
    state.taskTypeList = res.content;
  });

  // 获取工单子类
  QUERY_DICT_BY_PARENT_ID({
    parentTag: 'task_sub_type',
  }).then((res) => {
    if (!res.content || !res.content.length) return;
    state.taskSubTypeList = res.content;
  });

  // 运送工具
  QUERY_DICT_BY_PARENT_ID({
    parentTag: 'deliver_tool',
  }).then((res) => {
    if (!res.content || !res.content.length) return;
    state.deliverToolList = res.content;
  });
  // 运送工单来源集合
  QUERY_DICT_BY_PARENT_ID({
    parentTag: 'task_source',
  }).then((res) => {
    if (!res.content || !res.content.length) return;
    const orderSource = res.content.find((item) => item.dictTag === 'task_app');
    formState.orderSourceId = orderSource?.id;
    formState.orderSourceCode = orderSource?.dictTag;
    formState.orderSourceName = orderSource?.dictName;
  });
});

watch([() => state.taskTypeList, () => state.taskSubTypeList], () => {
  if (!state.taskTypeList.length || !state.taskSubTypeList.length) {
    return;
  }
  //封装级联结构数据
  state.taskTypeList.forEach((item) => {
    let deliverType: DeliverType = { text: item.dictName, value: item.id, children: [] };
    state.taskSubTypeList.forEach((subItem) => {
      if (subItem.dictTag.includes(item.dictTag)) {
        deliverType.children.push({ text: subItem.dictName, value: subItem.id });
      }
    });
    state.deliverTypeList.push(deliverType);
  });
});
</script>

<template>
  <view class="deliver-edit app-page--1">
    <app-navbar title="运送申请" />
    <nut-tabs
      model-value="push"
      class="deliver-edit__tabs"
      @click="
        ({ paneKey }) => {
          if (paneKey === 'record') {
            reLaunch({ url: '/pages/deliver/list/index?pageType=report-history' });
          }
        }
      "
    >
      <nut-tab-pane title="新建运送" pane-key="push" />
      <nut-tab-pane title="申请记录" pane-key="record" />
    </nut-tabs>
    <scroll-view class="app-page__wrapper" :scroll-y="true" :lower-threshold="100">
      <view class="deliver-edit__wrapper">
        <nut-form
          :model-value="formState"
          :rules="formRules"
          class="deliver-edit__form"
          ref="workOrderFormRef"
          body-align="right"
        >
          <nut-form-item
            required
            label="运送类型"
            prop="orderTypeId"
            label-align="left"
            error-message-align="left"
          >
            <nut-input
              :model-value="state.deliverType"
              placeholder="请选择运送类型"
              :border="false"
              readonly
              input-align="right"
              @click="state.taskTypePickerIsShow = !state.taskTypePickerIsShow"
            />
          </nut-form-item>
          <nut-form-item
            required
            label="计划时间"
            prop="planTimeStart"
            label-align="left"
            error-message-align="left"
          >
            <nut-input
              :model-value="state.deliverPlanTime"
              placeholder="请选择计划时间"
              :border="false"
              readonly
              @click="state.taskTimePickerVisible = !state.taskTimePickerVisible"
              input-align="right"
            />
          </nut-form-item>
          <nut-form-item
            required
            label="出发地"
            prop="areaNameStart"
            label-align="left"
            error-message-align="left"
          >
            <nut-input
              :model-value="formState.areaNameStart"
              placeholder="请选择出发地"
              :border="false"
              readonly
              @click="
                () => {
                  state.currentSelectedArea = 1;
                  state.appRegionListPopupIsShow = !state.appRegionListPopupIsShow;
                }
              "
              input-align="right"
            />
          </nut-form-item>
          <nut-form-item
            required
            label="目的地"
            prop="areaNameEnd"
            label-align="left"
            error-message-align="left"
          >
            <nut-input
              :model-value="formState.areaNameEnd"
              placeholder="请选择目的地"
              :border="false"
              readonly
              @click="
                () => {
                  state.currentSelectedArea = 2;
                  state.appRegionListPopupIsShow = !state.appRegionListPopupIsShow;
                }
              "
              input-align="right"
            />
          </nut-form-item>
          <nut-form-item
            required
            label="运送工具"
            prop="deliverToolId"
            label-align="left"
            error-message-align="left"
          >
            <nut-input
              :model-value="formState.deliverToolName"
              placeholder="请选择运送工具"
              :border="false"
              readonly
              @click="state.appDeliverToolListPopupIsShow = !state.appDeliverToolListPopupIsShow"
              input-align="right"
            />
          </nut-form-item>
          <nut-form-item label="患者信息" label-align="left" error-message-align="left">
            <nut-input
              class="deliver-edit__form-asset-input"
              v-model="formState.patientInfo"
              placeholder="请填写患者信息"
              :border="false"
              input-align="right"
            />
          </nut-form-item>
          <nut-form-item label="工单描述" />
          <nut-form-item>
            <nut-textarea
              v-model="formState.description"
              placeholder="填写申请说明"
              rows="8"
              limit-show
              text-align="left"
              max-length="200"
            />
          </nut-form-item>
          <nut-form-item label="上传图片">
            <app-upload-image @on-change="uploadImageChange" module="repair" :max="3" />
          </nut-form-item>
        </nut-form>
      </view>
    </scroll-view>
    <view class="deliver-edit__footer">
      <nut-button block type="info" @click="submit"> 提交 </nut-button>
    </view>

    <nut-popup
      v-model:visible="state.taskTypePickerIsShow"
      position="bottom"
      v-if="state.deliverTypeList.length > 0"
    >
      <nut-picker
        title="请选择工单类型"
        :model-value="[formState.orderTypeId as string]"
        :columns="state.deliverTypeList"
        @confirm="
          ({ selectedValue, selectedOptions }) => {
            if (!selectedValue[0]) return;

            formState.orderTypeCode =
              state.taskTypeList[
                state.taskTypeList.findIndex((t) => {
                  return t.id === selectedValue[0];
                })
              ].dictTag;
            formState.orderTypeId = selectedOptions[0].value;
            formState.orderTypeName = selectedOptions[0].text;

            formState.orderSubTypeCode =
              state.taskSubTypeList[
                state.taskSubTypeList.findIndex((t) => {
                  return t.id === selectedValue[1];
                })
              ].dictTag;
            formState.orderSubTypeId = selectedOptions[1].value;
            formState.orderSubTypeName = selectedOptions[1].text;
            state.deliverType = `${formState.orderTypeName} - ${formState.orderSubTypeName}`;
            state.taskTypePickerIsShow = false;
          }
        "
        @cancel="state.taskTypePickerIsShow = false"
      />
    </nut-popup>
    <app-time-range-picker-popup
      v-model="state.taskTimePickerVisible"
      :type="'datetime'"
      @on-selected="selectedTimeRange"
    ></app-time-range-picker-popup>
    <app-region-tree-popup
      v-model="state.appRegionListPopupIsShow"
      @on-selected="(id:string, name:string) => {
        if(state.currentSelectedArea === 1){
          formState.areaIdStart = id;
          formState.areaNameStart = name;
        }else if(state.currentSelectedArea === 2){
          formState.areaIdEnd = id;
          formState.areaNameEnd = name;
        }
      }"
    />

    <nut-popup
      v-model:visible="state.appDeliverToolListPopupIsShow"
      position="bottom"
      v-if="state.deliverToolList.length > 0"
    >
      <nut-picker
        title="请选择运送工具"
        :model-value="[formState.orderTypeId as string]"
        :columns="
          state.deliverToolList.map((v) => {
            return { text: v.dictName, value: v.id };
          })
        "
        @confirm="
          ({ selectedValue, selectedOptions }) => {
            if (!selectedValue[0]) return;

            formState.deliverToolCode =
              state.taskTypeList[
                state.deliverToolList.findIndex((t) => {
                  return t.id === selectedValue[0];
                })
              ].dictTag;
            formState.deliverToolId = selectedOptions[0].value;
            formState.deliverToolName = selectedOptions[0].text;

            state.appDeliverToolListPopupIsShow = false;
          }
        "
        @cancel="state.appDeliverToolListPopupIsShow = false"
      />
    </nut-popup>
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
